<?php

namespace app\zyhsapi\model\comment;

use app\common\cachemodel\ZlcrAstr;
use app\common\lib\Util;
use app\zyhsapi\model\BaseCacheZyhs;
use app\zyhsapi\model\ZyhsAstrBindUser;
use app\zyhsapi\model\ZyhsBlacklist;
use app\zyhsapi\model\ZyhsInteractiveMessage;
use app\zyhsapi\model\ZyhsPxyzUserQuestion;
use app\zyhsapi\model\ZyhsUser;
use XznsTools\cache\zyhs\CacheManageZyhs;

class ZyhsArticleCommentReply extends BaseCacheZyhs
{
    protected $table = 'good_wechat.zyhs_article_comment_reply';

    protected $cacheModel = 'zyhs.content_comment_reply';

    /**
     * 回复评论
     * @param array $userInfo
     * @param array $data
     * @return array
     */
    public function replyAdd(array $userInfo, array $data = [])
    {
        try
        {
            // 获取 用户绑定咨询师信息
            $userBindAstrInfo = (new ZyhsAstrBindUser())->getAstrBindUserData();
            $cacheKey = 'comment_num';
            $articleModel = new ZyhsPxyzUserQuestion();
            $zyhsArticleCommentModel = new ZyhsArticleComment();
            $commentInfo = $zyhsArticleCommentModel->getInfoById($data['comment_id'], ['uid', 'status', 'type', 'aid', 'reply_num', 'good_num']);
            if ($commentInfo['status'] !== 1)
            {
                return [
                    'status' => false,
                    'msg' => '服务异常，请稍后再试',
                ];
            }
            $sendUid = $commentInfo['uid'];
            if ($data['pid'])
            {
                $replyInfo = $this->getInfoById($data['pid'], ['uid', 'comment_id', 'status']);
                if (!$replyInfo || $replyInfo['status'] !== 1 || $replyInfo['comment_id'] !== $data['comment_id'])
                {
                    return [
                        'status' => false,
                        'msg' => '服务异常，请稍后再试',
                    ];
                }
                $data['uid2'] = $replyInfo['uid'];
                $sendUid = $replyInfo['uid'];
            }
            //获取对应的内容信息
            switch ($commentInfo['type'])
            {
                case 1:
                    $article = $articleModel->getInfoById($commentInfo['aid'], ['comment_num', 'uid', 'avatar_id', 'nickname', 'good_num', 'read_num', 'status']);
                    if ($article['status'] !== 1)
                    {
                        return [
                            'status' => false,
                            'msg' => '服务异常，请稍后再试',
                        ];
                    }
                    break;
                default:
                    $article = [];
            }
            if ($article)
            {   //  添加 评论回复
                $replyId = (int)$this->insertGetId($data);
                //  添加 时间排序
                $this->listDataAdd($data['comment_id'], [$replyId => $data['create_time']]);
                // 更新 评论 评论数 ---------------------------------------------------------------
                (new ZyhsArticleComment())->updateReplyNumData($data['comment_id'], 'reply_num', [
                    'good_num' => $commentInfo['good_num'],    // 点赞数
                    'reply_num' => $commentInfo['reply_num'], // 评论总数
                ]);
                switch ($commentInfo['type'])
                {
                    case 1:
                        // 更新 内容 评论数 ---------------------------------------------------------------
                        $d = [
                            'good_num' => $article['good_num'],    // 点赞数
                            'comment_num' => $article['comment_num'], // 评论总数
                            'read_num' => $article['read_num'],    // 已读总数
                        ];
                        $articleModel->updateCommentNumData($commentInfo['aid'], $cacheKey, $d);
                        // 添加 用户互动消息 ---------------------------------------------------------------
                        if ($sendUid !== $userInfo['id'])
                        {   //  不是 自己给自己  评论回复的情况下  添加互动消息
                            $blacklistUids = (new ZyhsBlacklist())->getBlackUids(1, $sendUid); // 获取 被通知用户 黑名单 uid
                            if (!$blacklistUids || !in_array($userInfo['id'], $blacklistUids))
                            {   // 黑名单为空 或 不是 黑名单用户
                                $d = [
                                    'atype' => 1,
                                    'aid' => $commentInfo['aid'],
                                    'type' => $data['pid'] > 0 ? 4 : 3,
                                    'comment_id' => $data['comment_id'],
                                    'reply_id' => $data['pid'],
                                    'uid' => $sendUid,
                                    'uid1' => $userInfo['id'],
                                    'res_id' => $replyId,
                                ];
                                (new ZyhsInteractiveMessage())->saveData($d);
                            }
                        }
                        //  添加我参与的 ---------------------------------------------------------------
                        (new ZyhsArticleMyInteracted())->setMyInteracted($userInfo['id'], 1, $commentInfo['aid'], $data['comment_id'], $replyId);
                        break;
                }
            } else
            {
                return [
                    'status' => false,
                    'msg' => '请求异常，请稍后再试～',
                ];
            }

        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return [
                'status' => false,
                'msg' => '服务异常，请稍后再试',
            ];
        }
        // 组合 返回输出数据
        $resData = [];
        switch ($commentInfo['type'])
        {
            case 1:
                $astrId = $userBindAstrInfo[$userInfo['id']] ?? 0;
                if ($astrId)
                {   // 占星师 回复 消息  头像 和昵称 使用占星师 的头像和昵称
                    $astrInfo = (new ZlcrAstr())->getInfoById($astrId, ['avatar', 'nickname']);
                    $avatar = $astrInfo['avatar'];
                    $nickname = $astrInfo['nickname'];
                } else
                {
                    if ($userInfo['id'] === $article['uid'])
                    {
                        $avatarNicknameList = config('pxyz.avatar_list');
                        $avatar = $avatarNicknameList[$article['avatar_id']];
                        $nickname = $article['nickname'];
                        $ownerTag = '本体';
                    } else
                    {
                        $avatar = $userInfo['avatar'];
                        $nickname = $userInfo['nickname'];
                    }
                }
                if ($data['pid'])
                {   // 有 @
                    if ($sendUid === $userInfo['id'])
                    {   // @自己
                        $nickname2 = $nickname;
                    } elseif (isset($userBindAstrInfo[$sendUid]))
                    {   // @占星师
                        $astrInfo = (new ZlcrAstr())->getInfoById($userBindAstrInfo[$sendUid], ['nickname']);
                        $nickname2 = $astrInfo['nickname'];
                    } elseif ($sendUid === $article['uid'])
                    {   // @作者
                        $nickname2 = $article['nickname'];
                    } else
                    {
                        $userInfo2 = (new ZyhsUser())->getInfoById($sendUid, ['nickname']);
                        $nickname2 = $userInfo2['nickname'];
                    }
                }
                $resData = [
                    'id' => $replyId,
                    'avatar' => $avatar,
                    'nickname' => $nickname,
                    'nickname2' => $nickname2 ?? '',
                    'create_time' => '刚刚',
                    'content' => $data['content'],
                    'good_num' => 0,
                    'is_good' => 0,
                    'is_self' => 1,
                    'astr_id' => $astrId,
                    'owner_tag' => $ownerTag ?? '',
                ];
                break;
        }

        return [
            'status' => true,
            'id' => $replyId,
            'data' => $resData,
        ];
    }

    /**
     * 评论 回复删除
     * @param int $commentReplyId
     * @param int $commentId
     * @return bool
     */
    public function replyDel(int $commentReplyId, int $commentId)
    {
        try
        {   // 评论 删除
            $this->where(['id' => $commentReplyId])->update(['status' => 0, 'del_type' => 1, 'delete_time' => time()]);

            CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $commentReplyId)->rmCache();

            $this->listDataDel($commentId, [$commentReplyId]);
            return true;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return false;
        }
    }

    /**
     * 重写数据时获取数据
     * @param $ids
     * @param $type
     * @param $sortType
     * @return array|false|string
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            $data = $this->where('id', 'in', $ids)
                ->column('id,uid,uid2,status,comment_id,pid,content,good_num,del_type,del_aid,create_time,delete_time', 'id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }

        return $data;
    }

    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        return $this->dataInit($resData);
    }

    public function dataInit(array $resData): array
    {
        foreach ($resData as $orderId => $questionItemData)
        {
            $resData[$orderId] = arrayKeyData2int($questionItemData, ['id', 'status', 'uid', 'uid2', 'comment_id', 'pid', 'good_num', 'del_type', 'del_aid', 'create_time', 'delete_time']);
        }
        return $resData;
    }

    public function getCommentReplyPageListIds(int $commentId)
    {
        $resData = CacheManageZyhs::getInstance()
            ->setCacheConfig($this->cacheModel, $commentId)
            ->setPage(-1)
            ->setSort('desc')
            ->getListPageDataIds(function ($isCache = true, $sortType = 'desc') use ($commentId)
            {
                try
                {
                    $data = $this->where(['status' => 1, 'comment_id' => $commentId])->order('create_time ' . $sortType)->column('create_time', 'id');
                    $resData = [];
                    foreach ($data as $id => $createTime)
                    {
                        $resData[$id] = ['create_time' => $createTime];
                    }

                    return $resData;
                }
                catch (\Exception $e)
                {
                    return [];
                }
            }, 'create_time', 0);

        return $resData['data'] ? array_keys($resData['data']) : [];
    }

    /**
     * @param int $commentId
     * @param int $type 1=>全部 2=>只看用户
     * @param int $minId
     * @param array $blacklistUids 排除的黑名单用户uid    用户过滤黑名单评论
     * @param array $userBindAstrInfo
     * @param array $field
     * @param int $limit
     * @return array
     * @throws \Exception
     */
    public function getRecommendCommentReplyDataList(int $commentId, int $type, int $minId, array $blacklistUids = [], array $userBindAstrInfo = [], array $field = [], int $limit = 10)
    {
        $allIds = $this->getCommentReplyPageListIds($commentId);

        $resDataList = [];
        $surplusNum = 0;
        $newMinId = 0;
        foreach ($allIds as $idItem)
        {
            if ($minId > 0 && $idItem >= $minId) continue;

            if (count($resDataList) >= $limit)
            {
                $surplusNum++;
            } else
            {
                $dataItem = $this->getInfoById($idItem, $field);
                if ($dataItem && !in_array($idItem['uid'], $blacklistUids, true))
                {
                    if ($type === 2 && isset($userBindAstrInfo[$dataItem['uid']]))
                    {   // 只看用户  过滤占星师回复
                        continue;
                    }
                    $resDataList[] = $dataItem;
                    $newMinId = $idItem;
                }
            }
        }

        return [
            'total' => count($allIds),
            'surplus_num' => $surplusNum,
            'min_id' => $newMinId,
            'data' => $resDataList,
        ];
    }

    /**
     * 获取 评论ID
     * @param int $uid
     * @param int $cid
     * @param int $type 1=>全部 2=>只看用户
     * @param int $minId
     * @param int $limit
     * @return array
     * @throws \Exception
     */
    public function getCommentReplyList(int $uid, int $cid, int $type, int $minId, int $limit = 10)
    {
        $zyhsArticleCommentModel = new ZyhsArticleComment();
        $commentInfo = $zyhsArticleCommentModel->getInfoById($cid, ['uid', 'status', 'type', 'aid']);
        if (!$commentInfo || $commentInfo['status'] !== 1)
        {
            return ['total' => 0, 'surplus_num' => 0, 'data' => [],];
        }
        switch ($commentInfo['type'])
        {
            case 1:
                $articleInfo = (new ZyhsPxyzUserQuestion())->getInfoById($commentInfo['aid'], ['uid', 'status', 'avatar_id', 'nickname']);
                break;
            default:
                $articleInfo = null;
        }
        if (!$articleInfo || $articleInfo['status'] !== 1)
        {   // 内容不存在  返回数据为空
            return ['total' => 0, 'surplus_num' => 0, 'data' => [],];
        }
        // 获取 黑名单用户 uid
        $blacklistUids = (new ZyhsBlacklist())->getBlackUids(1, $uid);
        //  获取绑定 占星师 的用户列表
        $userBindAstrInfo = (new ZyhsAstrBindUser())->getAstrBindUserData();
        $pageData = $this->getRecommendCommentReplyDataList($cid, $type, $minId, $blacklistUids, $userBindAstrInfo, ['uid', 'create_time', 'content', 'good_num', 'id', 'uid2'], $limit);
        //  用户点赞 评论回复ids列表
        $zyhsArticleCommentGoodModel = new ZyhsArticleCommentGood();
        $goodCommentReplyIds = $uid ? $zyhsArticleCommentGoodModel->getUserCommentGoodCids($uid, 2) : [];
        $resData = [];
        $avatarNicknameConfig = config('pxyz');
        foreach ($pageData['data'] as $datum)
        {
            if ($articleInfo['uid'] === $datum['uid'])
            {   // 发布内容 的 评论   【本人】
                $replyAvatar = $avatarNicknameConfig['avatar_list'][$articleInfo['avatar_id']];
                $replyNickname = $articleInfo['nickname'];
            } else
            {   // 非本人
                $userAvatarNicknameData = $zyhsArticleCommentModel->getUserAvatarNickname($datum['uid'], $userBindAstrInfo);
                $replyAvatar = $userAvatarNicknameData['avatar'];
                $replyNickname = $userAvatarNicknameData['nickname'];
            }
            if ($datum['uid2'])
            {   // 获取@用户uid
                if ($articleInfo['uid'] === $datum['uid2'])
                {   // 发布内容 的 评论   【本人】
                    $nickname2 = $articleInfo['nickname'];
                } else
                {
                    $userAvatarNicknameData = $zyhsArticleCommentModel->getUserAvatarNickname($datum['uid2'], $userBindAstrInfo);
                    $nickname2 = $userAvatarNicknameData['nickname'];
                }
            }
            $resData[] = [
                'id' => $datum['id'],
                'avatar' => $replyAvatar,
                'nickname' => $replyNickname,
                'nickname2' => $nickname2 ?? '',
                'create_time' => Util::timeToStr($datum['create_time']),
                'content' => $datum['content'],
                'good_num' => $datum['good_num'],
                'is_good' => in_array($datum['id'], $goodCommentReplyIds, true) ? 1 : 0,
                'is_self' => $datum['uid'] === $uid ? 1 : 0,
                'owner_tag' => $datum['uid'] === $articleInfo['uid'] ? '本体' : '',
            ];
        }
        $pageData['data'] = $resData;
        return $pageData;
    }

    /**
     * @param $crId
     * @param int $oldGoodNum
     * @param int $inc
     * @return void
     * @throws \Exception
     */
    public function updateReplyGoodNum($crId, int $oldGoodNum, int $inc = 1): void
    {
        $cache = CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $crId);
        $oldGoodNum = $oldGoodNum + $inc;
        if ($inc < 0 && $oldGoodNum < 0)
        {
            $oldGoodNum = 0;
            $cache->setCache(['good_num' => 0]);
        } else
        {   // 更新 缓存
            $cache->setCacheInc('good_num', 'details', $inc);
        }
        // 基数记录增加   用于减少更新数据库频率
        $addNum = $cache->setCacheKeyDetail('inc_base_num', $crId)->setCacheInc('good_num', 'inc_base_num', 1);
        if ($addNum > ($cache->cacheKey['base_max'] ?? 5))    // 咨询师 回复时 必须更新
        {   // 删除记录
            $cache->rmCache('inc_base_num');
            // 更新 入库
            $this->where(['id' => $crId])->update(['good_num' => $oldGoodNum]);
        }
    }
}